Practical-14
Mobile Application
Practical List
Create an android program to display the use of a custom component with extend TextView to Date View component.
Steps
- Create a new Android project in Android Studio.
- Open the
activity_main.xmllayout file. - Add a
com.example.dateview.DateViewelement to the layout with the following attributes:android:id="@+id/dateView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"
- Open the
MainActivity.javafile. - Inside the
onCreatemethod, add the following code to set the content view to theactivity_main.xmllayout:setContentView(R.layout.activity_main); - Create a new class called
DateViewthat extendsTextViewand override the necessary methods to display the current date:public class DateView extends TextView {
public DateView(Context context) {
super(context);
init();
}
public DateView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DateView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String currentDate = dateFormat.format(new Date());
setText(currentDate);
}
} - Open the
res/values/attrs.xmlfile and add the following code to define the custom attributes for theDateViewcomponent:<resources>
<declare-styleable name="DateView">
<attr name="dateFormat" format="string" />
</declare-styleable>
</resources> - Open the
res/layout/activity_main.xmlfile and add the following code to define the customDateViewcomponent:<com.example.dateview.DateView
android:id="@+id/dateView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp" /> - Run the application on an emulator or device to see the custom
DateViewcomponent displaying the current date.